<template>
  <div class="i-weditor">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="simple" />
    <Editor style="height: 500px; overflow-y: hidden;" @customPaste="customPaste" v-model="props.form[props.fieldKey!]" :defaultConfig="editorConfig" vop mode="simple" @onCreated="handleCreated" />
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig } from '@wangeditor/core';
import api from '@/api';
import config from '../../../config';
import { API } from '@/global';

const props = defineProps<{
  see: boolean,
  form: API.IParams,
  fieldKey: string,
}>()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const toolbarConfig = {}


const customPaste = (editor: IDomEditor, event: ClipboardEvent): boolean => {
  // 阻止默认的粘贴行为
  const text = event.clipboardData!.getData('text/plain')
  let _newVal = ''
  text.split('\n').forEach((res: string) => {
    _newVal += '<p>' + res + '</p>'
  })
  editor.dangerouslyInsertHtml(_newVal)

  event.preventDefault()
  return false
}

const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData()
        formData.append('file', file)
        // api.UploadImg(formData).then(({ data }: { data: IImgUploadForm }) => {
        //   const _url = config.baseUrl + data.img_url;
        //   data.message === '上传成功' && insertFn(_url, '图片加载失败', '')
        // })
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>   